﻿Imports ComponentFactory.Krypton.Toolkit
Imports System.Data.OleDb
Imports System.Runtime.InteropServices

Public Class ConsultaAutomovel
    Inherits KryptonForm

    Private conexao As OleDbConnection
    Private command As OleDbCommand
    Private dataSet As DataSet
    Private dataView As DataView
    Private dataAdapter As OleDbDataAdapter
    Private cmdBuilder As OleDbCommandBuilder
    Private strQueryAuto As String = "SELECT codAuto AS  Código " & _
                                        ", tblModeloAuto.descricaoModeloAuto " & _
                                        ", tblMontadoraAuto.descricaoMontadoraAuto " & _
                                        ", chassiAuto " & _
                                        ", tblCliente.nomeCliente " & _
                                        ", placaAuto " & _
                                        ", tblCombustivel.descricaoCombustivel " & _
                                        ", anofabricacaoAuto  " & _
                                        ", observacaoAuto  " & _
                                        ", tblCorAuto.descricaocorAuto  " & _
                                        ", potenciaMotor  " & _
                                        ", tblEstado.siglaEstado  " & _
                                        " FROM ((((((tblAuto" & _
                                        " LEFT JOIN tblModeloAuto ON tblModeloAuto.codmodeloAuto = tblAuto.codmodeloAuto)" & _
                                        " LEFT JOIN tblMontadoraAuto ON tblMontadoraAuto.codmontadoraAuto = tblAuto.codmontadoraAuto)" & _
                                        " LEFT JOIN tblCliente ON tblCliente.codCliente = tblAuto.codCliente)" & _
                                        " LEFT JOIN tblCombustivel ON tblCombustivel.codCombustivel = tblAuto.codCombustivel) " & _
                                        " LEFT JOIN tblCorAuto ON tblCorAuto.codcorAuto = tblAuto.codcorAuto)" & _
                                        " LEFT JOIN tblEstado ON tblEstado.codEstado = tblAuto.codEstado)"

    Private strTipoFiltro = Nothing

    Sub New()
        ' This call is required by the Windows Form Designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.

        strTipoFiltro = "Proprietario like '%{0}%'"

        cbtipopesquisa.SelectedIndex = 0

        conexao = FabricaDeConexoes.CriarConexao()
        dataSet = New DataSet()

        carregarAuto()
    End Sub

    Private Sub carregarAuto()
        Try
            Debug.WriteLine(strQueryAuto)
            If (dataSet IsNot Nothing) Then
                dataAdapter = New OleDbDataAdapter(strQueryAuto, conexao)
                dataSet = New DataSet()
                dataAdapter.Fill(dataSet, "tblAuto")

                dataView = New DataView(dataSet.Tables("tblAuto"), Nothing, "Código", DataViewRowState.CurrentRows)

                dtgautomovel.DataSource = dataView
                dtgautomovel.Columns(0).Visible = False
                dtgautomovel.Columns(1).HeaderText = "Modelo"
                dtgautomovel.Columns(2).HeaderText = "Montadora"
                dtgautomovel.Columns(3).HeaderText = "Chassi"
                dtgautomovel.Columns(4).HeaderText = "Proprietário"
                dtgautomovel.Columns(5).HeaderText = "Placa"
                dtgautomovel.Columns(6).HeaderText = "Combustível"
                dtgautomovel.Columns(7).HeaderText = "Ano do Auto"
                dtgautomovel.Columns(8).HeaderText = "Observacao"
                dtgautomovel.Columns(9).HeaderText = "Cor"
                dtgautomovel.Columns(10).HeaderText = "Potencia"
                dtgautomovel.Columns(11).HeaderText = "Estado"
            End If
        Catch ex As Exception
            Debug.WriteLine(ex)
        End Try
    End Sub

    Private Sub btnFechar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFechar.Click
        Me.Dispose()
    End Sub

    Private Sub btnNovo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNovo.Click
        Try
            Dim frmcad As New CadastroAutomovel()
            frmcad.ShowDialog()
            carregarAuto()
        Catch ex As Exception
            Debug.WriteLine(ex.StackTrace)
        End Try
    End Sub

    Private Sub cbtipopesquisa_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbtipopesquisa.SelectedIndexChanged
        txtfiltrar.Clear()
        txtfiltrar.Focus()

        Select Case (cbtipopesquisa.SelectedItem.ToString())

            Case "Proprietario"
                strTipoFiltro = "nomeCliente like '%{0}%'"
            Case "Placa"
                strTipoFiltro = "placaAuto like '%{0}%'"

            Case Else
                strTipoFiltro = Nothing
        End Select
    End Sub

    Private Sub txtfiltrar_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtfiltrar.TextChanged
        dataView.RowFilter = String.Format(strTipoFiltro, txtfiltrar.Text)
    End Sub

    Private Sub btnExcluir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExcluir.Click
        KryptonMessageBox.Show("Antes de excluir, verifique os dados do automóvel.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        btnImprimir.PerformClick()
        Dim resp = KryptonMessageBox.Show("Tem certeza que deseja excluir este cadastro?" & vbNewLine & "As alterações causadas pela exclusão são irreversíveis.", "Aviso", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If (resp = Windows.Forms.DialogResult.Yes) Then
            excluir()
        End If
    End Sub

    Private Sub btnEditar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEditar.Click
        Dim frm As New CadastroAutomovel(dtgautomovel.CurrentRow.Cells.Item(0).Value)
        frm.ShowDialog()
        Dim cmdBuilder As New OleDbCommandBuilder(dataAdapter)
        dataAdapter.Update(dataSet, "tblAuto")
        carregarAuto()
    End Sub

    Public Sub excluir()
        Try
            Dim queryAuto As String = "DELETE * FROM tblAuto WHERE tblAuto.codAuto = " & dtgautomovel.CurrentRow.Cells(0).Value

            'Abre conexão e exclui os veículos do cliente
            command = New OleDbCommand(queryAuto, conexao)
            conexao.Open()
            command.ExecuteNonQuery()

            'Faz a atualização do DataSet (esvazia e preenche novamente)
            cmdBuilder = New OleDbCommandBuilder(dataAdapter)
            dataSet.Tables("tblAuto").Clear()
            dataAdapter.Update(dataSet, "tblAuto")

            'Atualiza o DataGridView
            dataView.Table = dataSet.Tables("tblAuto")
            dtgautomovel.DataSource = dataView

            carregarAuto()

        Catch ex As OleDbException
            Debug.WriteLine("Erro: " & ex.Message)
        Finally
            command.Dispose()
            conexao.Close()
        End Try

    End Sub

    Private Sub btnImprimir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImprimir.Click
        VisualizadorRelatorio.gerarRelatorio("SELECT tblAuto.*,tblModeloAuto.descricaomodeloAuto,tblMontadoraAuto.descricaomontadoraAuto,tblCliente.nomeCliente,tblCorAuto.descricaocorAuto,tblCombustivel.descricaoCombustivel,tblEstado.descricaoEstado FROM ((((((tblAuto INNER JOIN tblModeloAuto ON tblModeloAuto.codmodeloAuto = tblAuto.codmodeloAuto) INNER JOIN tblEstado ON tblEstado.codEstado = tblAuto.codEstado)INNER JOIN tblMontadoraAuto ON tblMontadoraAuto.codmontadoraAuto = tblAuto.codmontadoraAuto) INNER JOIN tblCliente ON tblCliente.codCliente = tblAuto.codCliente) INNER JOIN tblCorAuto ON tblCorAuto.codCorAuto = tblAuto.codCorAuto)INNER JOIN tblCombustivel ON tblCombustivel.codCombustivel = tblAuto.codCombustivel) WHERE tblAuto.codAuto = " & dtgautomovel.CurrentRow.Cells(0).Value _
                                            , "tblAuto" _
                                            , Config.DiretorioAplicacao & "/../../../Relatorio/relatorioIndivAuto.rpt")
    End Sub
End Class